<?php
namespace frontend\models\record;

use Yii;
use yii\base\Model;
use yii\db\Query;
//use frontend\models\PostGroup;

class PostGroupAudit extends Model
{
    /**
    post_group_audit(draft)
    |- id group_name cover intro keywords owner_uid category_ids audit_state audit_desc
     */
    public $group_name;
    public $keywords;
    public $intro;
    public $category_ids;

    public $owner_uid;
    public $create_at;
    public $state;

    public static function tableName() {
        return 'post_group_audit';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['group_name', 'required'],
            ['keywords', 'required'],
            ['intro', 'required'],
            ['category_ids', 'required'],
        ];
    }

    public function createPostGroup()
    {
        $error_array = array();
        $error_array['code'] = 1;
        $error_array['msg'] = 'unknown';
        if (!$this->validate()) {
            $error_array['msg'] = 'invalid field';
            return $error_array;
        }

        $count_cate_sel = 0;
        if($this->category_ids != null
                && is_array($this->category_ids)) {
            $count_cate_sel = count($this->category_ids);
        }

        if($count_cate_sel <= 0) {
            $error_array['msg'] = 'no select category';
            return $error_array;
        }

        if(Yii::$app->user->isGuest) {
            $error_array['msg'] = 'no user';
            return $error_array;
        }

        $query = new Query;
        $exists_in_post_group = $query->select(['id'])
            ->from(PostGroup::tableName())
            ->where('group_name=:group_name', [
                ':group_name' => $this->group_name,
            ])
            ->createCommand(Yii::$app->db)
            ->queryScalar();
        if($exists_in_post_group === false) {
            $this->owner_uid = Yii::$app->user->identity->id;
            $this->create_at = time();
            try {
                Yii::$app->db->createCommand()
                    ->insert($this->tableName(), [
                        'group_name' => $this->group_name,
                        'keywords' => $this->keywords,
                        'intro' => $this->intro,
                        'owner_uid' => $this->owner_uid,
                        'create_at' => $this->create_at,
                        'audit_state' => 1,//待审核
                        'audit_desc' => '待审核',//待审核
                    ])
                    ->execute();
                $id = Yii::$app->db->getLastInsertID();
                $error_array['code'] = 0;
                $error_array['msg'] = 'succed';
            } catch(\Exception $e) {
                $error_array['msg'] = 'insert failed';
            }
        } else {
            $error_array['msg'] = 'exists group name';
        }

        return $error_array;
    }
}
